package com.zrf.base.knowledge.point.offer.chapter1;

/**
 * @author zhouruifeng
 * @date 2020-10-21
 */
public class Singleton {

    public static void main(String[] args) {
        new Thread(()-> System.out.println(Dcl.getInstance())).start();
        new Thread(()-> System.out.println(Dcl.getInstance())).start();
    }

    /**
     * double check lock
     * 通过反射可以破坏该条件
     */
    public static class Dcl {
        private static volatile Object instance = null;

        public static Object getInstance() {
            if (instance == null) {
                synchronized (Dcl.class) {
                    if (instance == null) {
                        instance = new Object();
                    }
                }
            }
            return instance;
        }
    }

    /**
     * 通过反射可以破坏该条件
     */
    public static class StaticInnerField {

        public static Object getInstance() {
            return Inner.instance;
        }


        static class Inner {
            public static final Object instance = new Object();
        }
    }

    public static class EnumItem {
        public static Object getInstance() {
            return Inner.INSTANCE;
        }

        enum Inner {
            INSTANCE;
        }
    }
}
